import { AmpIncludeAmpScript } from './AmpCustomElement'

type AmpScriptProps = {
  id?: string
  children?: React.ReactNode
  layout?: string
  width?: string
  height?: string
  script?: Function | string
  src?: string
}

const generateInlineScript = (script: Function | string) => {
  if (typeof script === 'function') {
    return `${script.toString()}()`
  }
  return String(script)
}

/**
 * Embeds an AMP Script by either linking to a TS `src` file or embedding inline
 * AMP Script via the `script` property. The inline script hash will automatically
 * be generated by AMP Optimizer.
 */
const AmpScript: React.FC<AmpScriptProps> = ({
  id,
  script,
  children,
  ...props
}) => {
  return (
    <>
      <AmpIncludeAmpScript />
      <amp-script script={id} {...props}>
        {children}
      </amp-script>
      {script && (
        <script
          id={id}
          type="text/plain"
          target="amp-script"
          dangerouslySetInnerHTML={{
            __html: generateInlineScript(script),
          }}
        />
      )}
    </>
  )
}

export default AmpScript
